import axios from 'axios'
import { ElMessageBox } from 'element-plus'
const request = axios.create({
  baseURL: '/api',
  timeout: 6000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截，把数据带出去
request.interceptors.request.use(
  // 参数配置
  // 请求前的判断是否有或者携带令牌
  (config) => {
    if (sessionStorage.getItem('token')) {
      // console.log(sessionStorage.getItem('token'))
      config.headers.token = sessionStorage.getItem('token')
    }

    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器

request.interceptors.response.use(
  (response) => {
    console.log(response)
    if (response.data.code == 0) {
      ElMessageBox.alert('认证失败请先注册再登录').then(() => {
        window.top.location.href = '/reg'
      })
    }
    return response
  },
  (error) => {
    switch (error.response.status) {
      case 401:
        ElMessageBox.alert('认证失败，请登录', '提醒').then(() => {
          window.top.location.href = '/reg'
        })
        break
      case 404:
        ElMessageBox.alert('请求资源不存在', '提醒')
        break
      case 500:
        ElMessageBox.alert('服务端异常', '提醒')
        break
      default:
        ElMessageBox.alert('未知错误', '提醒')
        break
    }
    return Promise.reject(error)
  }
)

export default request
